﻿using ASmile.Com;
using ASmile.DBModel;
using ASmile.Extend;
using ASmile.Helpers;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Linq;

namespace ASmile.Web
{
    /// <summary>
    /// WebApi请求验证
    /// </summary>
    public class UserAuthorizeAttribute : AuthorizeBaseAttribute
    {
        /// <summary>
        /// 默认已验证登陆权限初始化
        /// </summary>
        public UserAuthorizeAttribute() : this(true, true)
        { }
        /// <summary>
        /// 指定验证类型来验证登陆权限
        /// </summary>
        public UserAuthorizeAttribute(bool isAuth, bool isAuthRoleUrl = true)
        {
            IsAuth = isAuth;
            IsAuthRoleUrl = isAuthRoleUrl;
        }

        /// <summary>
        /// 验证失败的处理方法，返回401
        /// </summary>
        protected void AuthorizationFail(AuthorizationFilterContext context, int failCode = 0)
        {
            //验证失败，返回401 错误
            context.Result = new ContentResult() { Content = $"authorization fail,code:{failCode}", StatusCode = StatusCodes.Status401Unauthorized };
        }

        //LoginUser _CurrUser;

        //protected internal LoginUser CurrUser { get { return _CurrUser; } }

        protected override void AuthorizationHandle(AuthorizationFilterContext context)
        {
            if (!CheckFilter(context)) return;

            var token = context.HttpContext.GetToken();
            if (!LoginState.CheckToken(token, out LoginUser user))
            {
                AuthorizationFail(context,99);
                return;
            }

            var rCode = AuthorizationUserRole(context, user);
            if (rCode != 0)
            {
                AuthorizationFail(context, rCode);
            }

            /*

            if (!Config.THIS.VerifyRoleUrl) return;

            if (!IsAuthRoleUrl) return;

            if (CurrUser.RoleId.IsEmpty())
            {
                AuthorizationFail(context, 100);
                return;
            }
            
            var rList = DataCacheCom.GetRoleUrlByRoleId(CurrUser.RoleId);
            if (rList == null || rList.Count == 0)
            {
                AuthorizationFail(context, 101);
                return;
            }

            var path = context.HttpContext.Request.Path.Value;
            var ip = context.HttpContext.GetRemoteIp();
            //Console.WriteLine($"IP:{ip},Path:{path}");
            //匹配到IP返回true,否则未false
            bool MatchIP(Sys_RoleUrl m, int failCode)
            {
                if (!m.IsLimitIP) return true;
                if (m.IPStrs.IsNotEmpty())
                {
                    var ipArrs = m.IPStrs.Split(';', StringSplitOptions.RemoveEmptyEntries);
                    if (ipArrs.Contains(ip))
                    {
                        return true;
                    }
                }
                AuthorizationFail(context, failCode);
                return false;
            }

            foreach (var item in rList.OrderByDescending(s=>s.IsRefuse))
            {
                if (item.MatchMode == 1 && path.StartsWith(item.MatchValue, true, null))
                {
                    if (!MatchIP(item, 102)) return;
                    if (item.IsRefuse)
                    {
                        AuthorizationFail(context, 1021);
                        return;
                    }
                    return;
                }
                else if (item.MatchMode == 2 && path.EndsWith(item.MatchValue, true, null))
                {
                    if (!MatchIP(item, 103)) return;
                    if (item.IsRefuse)
                    {
                        AuthorizationFail(context, 1031);
                        return;
                    }
                    return;
                }
                else if (item.MatchMode == 3 && path.ContainsLike(item.MatchValue))
                {
                    if (!MatchIP(item, 104)) return;
                    if (item.IsRefuse)
                    {
                        AuthorizationFail(context, 1041);
                        return;
                    }
                    return;
                }
                else if (item.MatchMode == 4 && path.StringEquals(item.MatchValue))
                {
                    if (!MatchIP(item, 105)) return;
                    if (item.IsRefuse)
                    {
                        AuthorizationFail(context, 1051);
                        return;
                    }
                    return;
                }
                else if (item.MatchMode == 5 && RegexHelper.Check(path, item.MatchValue))
                {
                    if (!MatchIP(item, 106)) return;
                    if (item.IsRefuse)
                    {
                        AuthorizationFail(context, 1061);
                        return;
                    }
                    return;
                }
            }

            AuthorizationFail(context, 199);
            */
        }
    }
}